﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@
@namespace ThingsGateway.OPCUA

@using Masa.Blazor.Presets;
@using BlazorComponent;
@using Microsoft.AspNetCore.Components.Web;
@using Microsoft.JSInterop;
@using Opc.Ua.Client;
@using Opc.Ua;
@using ThingsGateway.Core;
@using ThingsGateway.Foundation;
@using ThingsGateway.Foundation.Extension;
@using ThingsGateway.Foundation.Serial;
@using ThingsGateway.Web.Foundation;
@using Masa.Blazor
@using TouchSocket.Core;
@inherits DriverDebugUIBase
<OPCUAClientPage @ref=tcpClientPage></OPCUAClientPage>

<MCard Class="pa-4" Flat Elevation="0">
    <MRow Class="my-1" NoGutters>

        <MCol Md="4">
            <MCard Flat Elevation="0">
                <MCol Class="my-1 py-1">
                    <MTextField Class="mx-1 my-1" Label="变量地址" Dense Outlined HideDetails="@("auto")" @bind-Value=@address />
                    <MRow NoGutters>
                        <MButton Class="mx-1 my-1" Color="primary" OnClick="Add">
                            添加
                        </MButton>
                        <MButton Class="mx-1 my-1" Color="primary" OnClick="Remove">
                            移除
                        </MButton>
                    </MRow>



                    <MButton Class="mx-1 my-1" Color="primary" OnClick="Read">
                        组读取
                    </MButton>



                    <MTextField Class="mx-1 mt-3 my-1" Label="值" Dense Outlined HideDetails="@("auto")" @bind-Value=@writeValue />
                    <MSelect Class="mx-1 my-1" Style="max-width:200px" @bind-Value="dataTypeEnum" Outlined Label="数据类型"
                             Items=@(typeof(DataTypeEnum).GetEnumList())
                             MenuProps="@(props => { props.Auto = true; props.OffsetY = true; })"
                             ItemText=@((u) =>u.des)
                             ItemValue=@(u =>(DataTypeEnum)u.value)
                             HideDetails=@("auto") Height="30"
                             Dense>
                    </MSelect>

                    <MButton Class="mx-1 my-1" Color="primary" OnClick="Write">
                        写入
                    </MButton>

                    <MRow NoGutters>

                        <MButton Class="mx-1 my-3" Color="primary" OnClick="()=>IsShowImportVariableList=!IsShowImportVariableList">
                            <span>导入变量</span>
                        </MButton>

                    </MRow>
                </MCol>
            </MCard>
        </MCol>

        <MCol Md="8">


            <MCard Height=@("calc(100vh - 420px)") Style="overflow-y:auto;width:100%" Elevation="0" Flat Class="ml-4">
                <MCardActions>
                    输出日志
                    <MSpacer></MSpacer>

                    <MTooltip Bottom Context="tip">
                        <ActivatorContent>
                            <MButton Loading=isDownExport Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small
                                     OnClick=@(async()=>
                                     {
                                     await DownDeviceMessageExport(Messages.Select(a=>a.message));
                                     }
                                     )>
                                <MIcon>mdi-export</MIcon>
                            </MButton>
                        </ActivatorContent>
                        <ChildContent>
                            <span>导出</span>
                        </ChildContent>
                    </MTooltip>

                </MCardActions>
                @{
                    var item = Messages;
                    <MRow Class="ml-2 mr-2 d-flex" NoGutters>
                        <MVirtualScroll Context="itemMessage" Height=@("calc(100vh - 500px)") OverscanCount=2 ItemSize="200" Items="item">
                            <ItemContent>
                                <div title=@itemMessage.message class=@(itemMessage.level<Microsoft.Extensions.Logging.LogLevel.Information?" black--text ":itemMessage.level>=Microsoft.Extensions.Logging.LogLevel.Warning?" red--text ":"green--text ") style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;">
                                    @itemMessage.message
                                </div>

                            </ItemContent>
                        </MVirtualScroll>
                    </MRow>
                }
            </MCard>
        </MCol>

    </MRow>

</MCard>

<PModal @bind-Value="IsShowImportVariableList" OnCancel="() => IsShowImportVariableList = false"
        Title=导入变量 Height=@("700") Persistent
        MaxWidth="1500" OnSave="DownDeviceExport">
    <ChildContent>
        @if (IsShowImportVariableList)
        {
            <ImportVariable @ref=importVariable PLC="_plc"></ImportVariable>
        }
    </ChildContent>


    <SaveContent Context="save">
        <MButton Text Color="primary" OnClick="save.Click" Disabled="isDownExport" Loading="isDownExport">
            <MLabel>导出Excel</MLabel>
        </MButton>
    </SaveContent>
</PModal>

@code {
    bool IsShowImportVariableList;
    private ImportVariable importVariable { get; set; }
}
@code
{
    private OPCUAClientPage tcpClientPage;
    private ThingsGateway.Foundation.Adapter.OPCUA.OPCUAClient _plc;

    private async Task DownDeviceExport()
    {
        var data = importVariable?.GetImportVariableList();
        if (data != null)
        {
            await DownDeviceExport(data?.Item1);
            await DownDeviceExport(data?.Item2);
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            tcpClientPage.LogAction = LogOut;
            //载入配置
            _plc = tcpClientPage.OPC;
            StateHasChanged();
        }

        base.OnAfterRender(firstRender);
    }

    private void Add()
    {
        if (_plc.Connected)
            _plc.AddSubscription("", address, callback);
        else
        {
            Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "未连接"));
            if (Messages.Count > 2500)
            {
                Messages.Clear();
            }
        }


    }
    private void callback(string arg1, MonitoredItem arg2, MonitoredItemNotificationEventArgs arg3)
    {
        var data = arg3.NotificationValue as MonitoredItemNotification;
        var t = new
        {
            name = arg2.DisplayName,
            type = data.Value.WrappedValue.TypeInfo.ToString(),
            value = data.Value.Value,
        };
        Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + t.ToJson().FormatJson()));
        if (Messages.Count > 2500)
        {
            Messages.Clear();
        }
    }

    private void Remove()
    {
        if (_plc.Connected)
            _plc.RemoveSubscription("");
        else
        {
            Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "未连接"));
            if (Messages.Count > 2500)
            {
                Messages.Clear();
            }
        }
    }
    public override async Task Read()
    {
        if (_plc.Connected)
        {
            var data = await _plc.ReadNodeAsync(address);
            Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + data.Select(a =>
            {
                return new
                {
                    code = a.StatusCode,
                    value = a.Value,
                };
            }).ToJson().FormatJson()));
            if (Messages.Count > 2500)
            {
                Messages.Clear();
            }
        }
        else
        {
            Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "未连接"));
            if (Messages.Count > 2500)
            {
                Messages.Clear();
            }
        }
    }

    public override async Task Write()
    {
        try
        {
            if (_plc.Connected)
            {
                var data = await _plc.WriteNodeAsync(address, Convert.ChangeType(writeValue, dataTypeEnum.GetNetType()));
                if (data.IsSuccess)
                {
                    Messages.Add((Microsoft.Extensions.Logging.LogLevel.Information, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + " - 写入成功"));
                }
                else
                {
                    Messages.Add((Microsoft.Extensions.Logging.LogLevel.Warning, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + " - 写入失败 " + data.Message));
                }
            }
            else
            {
                Messages.Add((Microsoft.Extensions.Logging.LogLevel.Debug, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "未连接"));
                if (Messages.Count > 2500)
                {
                    Messages.Clear();
                }
            }
        }
        catch (Exception ex)
        {
            Messages.Add((Microsoft.Extensions.Logging.LogLevel.Error, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + " - " + "写入失败：" + ex.Message));
        }
    }
    public override void Dispose()
    {
        _plc.SafeDispose();
        tcpClientPage.SafeDispose();
        base.Dispose();
    }
    public override string ToString()
    {
        return nameof(OPCUAClient);
    }
}